package net.caixiaomi.info.ui.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;
import com.sobot.chat.utils.VersionUtils;

import net.caixiaomi.info.Lottery.ui.BallLotteryMainActivity;
import net.caixiaomi.info.R;
import net.caixiaomi.info.base.BaseFragment;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.interfaces.MatchingSelectCallBack;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.CustomerModel;
import net.caixiaomi.info.model.LotteryItem;
import net.caixiaomi.info.model.MatchChooseDate;
import net.caixiaomi.info.model.MatchItem;
import net.caixiaomi.info.model.MatchResultNewModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.dialog.MatchFilterDialogFragment;
import net.caixiaomi.info.ui.dialog.TimeDialogFragment;
import net.caixiaomi.info.ui.matching.MatchItemFragment;
import net.caixiaomi.info.ui.view.MatchingSelectView;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

import static com.alibaba.fastjson.JSON.parseObject;

/**
 * Created by suntian on 2018/7/18.
 */

public class MatchFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener, OnRefreshListener, ViewPager.OnPageChangeListener,MatchingSelectCallBack {

    public static final String TAG = "MatchFragment";
    private MyFragmentPagerAdapter adapter;

    @BindView(R.id.title)
    TextView mTitle;

    @BindView(R.id.matching_select_view)
    MatchingSelectView mSelectView;

    @BindView(R.id.scroll_view)
    HorizontalScrollView scroll_view;

    @BindView(R.id.fragment_view_pager)
    ViewPager fragment_view_pager;

    @BindView(R.id.matching_date_iv)
    RelativeLayout mMatchingDateImg;

    @BindView(R.id.matching_setting_tv)
    RelativeLayout mMatchingSettingTv;

    @OnClick(R.id.matching_date_iv)
    void matchingDate(){
//        ToastUtil.s(AppHelper.getChanel(getActivity())+ VersionUtils.getVersionName(getActivity()));

//
//                ARouter.getInstance()
//                .build("/com/TestModule").withString("test","test")
//                .navigation();
//        Intent intent=new Intent(getActivity(), BallLotteryMainActivity.class);
//        startActivity(intent);

        try {
            String text = JSON.toJSONString(mTimeList);
            TimeDialogFragment dialog = new TimeDialogFragment();
            Bundle bundle = new Bundle();
            bundle.putString("data", text);
            dialog.setArguments(bundle);
            dialog.show(getFragmentManager(), dialog.getClass().getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.matching_setting_tv)
    void matchingSetting(){
        if (mMatchList != null) {
            String strData = JSON.toJSONString(mMatchList);
            MatchFilterDialogFragment dialog = new MatchFilterDialogFragment();
            Bundle bundle = new Bundle();
            bundle.putString("data", strData);
            bundle.putInt("planFilter", 0); //只看已购对阵去掉
            bundle.putString("isAlreadyBuyMatch", mIsAlreadyBuyMatch);
            dialog.setArguments(bundle);
            dialog.show(getFragmentManager(), MatchFilterDialogFragment.class.getName());
        }
    }

    private String mCurrentTime = "";
    private String mLeagueId = "";
//    private String mMatchFinish = "";
    private String mIsAlreadyBuyMatch = "";
    public int mType=0;
    private List<CustomerModel> mTimeList = new ArrayList<>();
    private List<MatchItem> mMatchList;
    private ArrayList<MatchItemFragment> mFragmentList;

    private MatchItemFragment mBeforeFragment;
    private MatchItemFragment mAfterFragment;
    private MatchItemFragment mMineFragment;

    public boolean mOnresume=true;

    public static MatchFragment newInstance() {
        return new MatchFragment();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    protected int fragmentLayout() {
        return R.layout.frag_matching;
    }

    @Override
    protected void onFragmentCreated(View view, @Nullable Bundle savedInstanceState) {
        mLoading = new DefLoading(getActivity());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getString(R.string.app_name)).append(" · ").append(getString(R.string.bottom_lottery));
        mTitle.setText(stringBuilder.toString());

        //view pager
        adapter = new MyFragmentPagerAdapter(getChildFragmentManager(),
                getFragmentList()
        );
        fragment_view_pager.setAdapter(adapter);
        fragment_view_pager.addOnPageChangeListener(this);
        fragment_view_pager.setOffscreenPageLimit(3);

        mSelectView.setCallBack(this);

//        createTimeList();
        filterConditions();
        getMatchChooseDate();

//        loadData(mType,false);
        setType(mType);
    }

    /**
     * 生成碎片列表
     */
    private ArrayList<MatchItemFragment> getFragmentList() {
        mFragmentList = new ArrayList<>();
        mBeforeFragment=MatchItemFragment.newInstance();
        mFragmentList.add(mBeforeFragment);
        mAfterFragment=MatchItemFragment.newInstance();
        mFragmentList.add(mAfterFragment);
        mMineFragment=MatchItemFragment.newInstance();
        mFragmentList.add(mMineFragment);
//        mBeforeFragment.setCallBack(mSelectView);
//        mAfterFragment.setCallBack(mSelectView);
//        mMineFragment.setCallBack(mSelectView);
        mBeforeFragment.setParent(this);
        mAfterFragment.setParent(this);
        mMineFragment.setParent(this);
        //此处省略......
        return mFragmentList;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    //判断当前fragment是否显示
    public void setCurrentFragmentOnresume(boolean onresume){
        mOnresume=onresume;
        if(mOnresume&&mBeforeFragment.getUserVisibleHint()) {
            mBeforeFragment.startTimerTask();
        }else{
            mBeforeFragment.cancelTimerTask();
        }
    }

    @Override
    public void onPageSelected(int position) {
        mType=position;
        mSelectView.setPageSelected(position);

        smoothScrollTo(position * mSelectView.subTitleWidth);

        mFragmentList.get(position).setRequestData(mCurrentTime,mLeagueId,String.valueOf(position),true);

        //
        if(mType==0) {
            mBeforeFragment.startTimerTask();
        }else{
            mBeforeFragment.cancelTimerTask();
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 流畅滑动
     */
    private void smoothScrollTo(final int scrollTo) {
        final int currentPosition = scroll_view.getScrollX();
        Animation anim = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                int scrollOffset = scrollTo - currentPosition;
                scroll_view.scrollTo(currentPosition + (int) (scrollOffset * interpolatedTime), 0);
            }
        };
        anim.setDuration(300);
        scroll_view.startAnimation(anim);
    }

    @Override
    public void matchingBarSelected(int position) {
        if(mType==position){
            loadData(mType,true);
        }
        fragment_view_pager.setCurrentItem(position);

    }
    /**
     * viewpager adapter
     */
    private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<MatchItemFragment> list;

        public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<MatchItemFragment> list) {
            super(fm);
            this.list = list;
        }

        @Override
        public Fragment getItem(int arg0) {
            return list.get(arg0);
        }

        @Override
        public int getCount() {
            return list.size();
        }

    }

//    private void createTimeList() {
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//        Calendar calendar = Calendar.getInstance();
//        Date currentDate = calendar.getTime();
//        String curDate = dateFormat.format(currentDate);
//        CustomerModel item = new CustomerModel();
//        item.setName(curDate);
//        item.setSelected(true);
//        mCurrentTime = item.getName();
//        mTimeList.add(item);
//        for (int index = 1; index < 8; index++) {
//            calendar.setTime(currentDate);
//            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - index);
//            item = new CustomerModel();
//            item.setName(dateFormat.format(calendar.getTime()));
//            mTimeList.add(item);
//        }
//
//        Collections.reverse(mTimeList);
//
//    }

    private void getMatchChooseDate(){
        JSONObject params = new JSONObject();
        params.put("emptyStr", "");
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<List<MatchChooseDate>>> filterConditions = requestService.getMatchChhooseDate(params);
        filterConditions.enqueue(new ResponseCallback<BaseCallModel<List<MatchChooseDate>>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<List<MatchChooseDate>> data) {
                if(data!=null) {
                    List<MatchChooseDate> list=data.data;
                    if(list!=null) {
                        for (int i = 0; i < list.size(); i++) {
                            MatchChooseDate entity=list.get(i);
                            CustomerModel item = new CustomerModel();
                            item.setName(entity.getStrDate());
                            item.setSelected(TextUtils.equals(entity.getIsSelected(),"1"));
                            if(TextUtils.equals(entity.getIsSelected(),"1")){

                            }
                            mTimeList.add(item);
                        }
                    }
                }
            }

            @Override
            public void onFail(ResponseError error) {
            }

            @Override
            public void onError() {
            }
        });
    }

    /**
     * 获取赛事列表
     */
    private void filterConditions() {
        JSONObject params = new JSONObject();
        params.put("dateStr", mCurrentTime);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<List<MatchItem>>> filterConditions = requestService.getFilterConditionsSomeDay(params);
        filterConditions.enqueue(new ResponseCallback<BaseCallModel<List<MatchItem>>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<List<MatchItem>> data) {
                mMatchList = data.data;
            }

            @Override
            public void onFail(ResponseError error) {
            }

            @Override
            public void onError() {
            }
        });
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_TIME:
                    mLoading.show();
                    mLeagueId = "";
//                    mMatchFinish = "";
//                    mAll.setText(R.string.C_ALL);
                    handlePostTime(event.getMessage());
                    filterConditions();
                    loadData(mType,true);
                    break;
                case EventWhat.EVENT_FOOTBALL_MATCH_FILTER:
                    mLoading.show();
                    handleMatchFilter(event.getMessage());
                    loadData(mType,true);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理选择时间返回结果
     */
    private void handlePostTime(String message) {
        try {
            mTimeList = parseObject(message, new TypeToken<List<CustomerModel>>() {
            }.getType());
            for (CustomerModel item : mTimeList) {
                if (item.isSelected()) {
                    mCurrentTime = item.getName();
                    break;
                }
            }
//            mTime.setText(mCurrentTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleMatchFilter(String message) {
        try {
            JSONObject object = parseObject(message);
            JSONArray dataArray = object.getJSONArray("data");
            mMatchList = parseObject(dataArray.toString(), new TypeToken<List<MatchItem>>() {
            }.getType());

            StringBuilder stringBuilder = new StringBuilder();
            for (MatchItem item : mMatchList) {
                if (item.isSelect()) {
                    stringBuilder.append(item.getLeagueId()).append(",");
                }
            }
            if (!TextUtils.isEmpty(stringBuilder)) {
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            }
            mLeagueId = stringBuilder.toString();
            mIsAlreadyBuyMatch = object.getString("isAlreadyBuyMatch");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void loadData(int position,boolean toTop){
        mFragmentList.get(position).setRequestData(mCurrentTime,mLeagueId,String.valueOf(position),toTop);
//        mBeforeFragment.setRequestData(mCurrentTime,mLeagueId,"0",false);
//        mAfterFragment.setRequestData(mCurrentTime,mLeagueId,"1",false);
//        mMineFragment.setRequestData(mCurrentTime,mLeagueId,"2",false);
        dismissLoading();
    }

    private void setType(int position){
        mFragmentList.get(position).setType(String.valueOf(position));
    }

}
